package com.gp.servlet.v1;

import com.gp.mvcframework.*;
import com.gp.myController.MyController;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

public class GPDispatcherServlet extends HttpServlet {

    private Properties contextConfig = new Properties();

    private List<String> classNames = new ArrayList<String>();

    private Map<String , Object> IOC = new HashMap<>();

    private Map<String , Method> handllerMapping = new HashMap<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        doDispatch(req, resp);

    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        //1.加载配置文件
        doLoadConfig(config.getInitParameter("contextConfigLocation"));

        //2.扫描相关的类
        doScanner(contextConfig.get("scanPackage").toString());

        //3.初始化所有的类的相关实例，并且放在IOC容器中
        doInstance();

        //4.依赖注入
        doAutowired();

        //5.初始化 HandlerMapping
        initHandlerMapping();

        System.out.println(" my spring framework is init.");

    }

    /**
     * 第一版， 参数传递是写固定的
     * @param req
     * @param resp
     */
    private void doDispatch_v1(HttpServletRequest req, HttpServletResponse resp) {

        // 绝对路径
        String url = req.getRequestURI();

        // 处理成相对路径
        String contextPath = req.getContextPath();

        url = url.replaceAll(contextPath, "").replaceAll("/+","/");

        if (!handllerMapping.containsKey(url)){
            try (PrintWriter writer = resp.getWriter()){
                writer.write("404 Not Found!!!");
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Method method = handllerMapping.get(url);

        String beanName = toLowerFirstCase(method.getDeclaringClass().getSimpleName());

        Map<String, String[]> params = req.getParameterMap();

        try {
            Object obj = IOC.get(beanName);
            Object[] paramArr = new Object[]{req, resp, params.get("name")[0]};
            method.invoke(obj, paramArr);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    /**
     *  这个方法示例是 错误的，在获取 方法形参 的注解一断，逻辑是错的，那样写只会获取类的注解
     *  在 v1 中反射调用 action 方法的时候参数是写死的参数名，这次修改将 参数改为活的
     * @param req
     * @param resp
     */
    private void doDispatch_v2(HttpServletRequest req, HttpServletResponse resp) {

        // 绝对路径
        String url = req.getRequestURI();

        // 处理成相对路径
        String contextPath = req.getContextPath();

        url = url.replaceAll(contextPath, "").replaceAll("/+","/");

        if (!handllerMapping.containsKey(url)){
            try (PrintWriter writer = resp.getWriter()){
                writer.write("404 Not Found!!!");
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Method method = handllerMapping.get(url);

        // action 方法所在的类名
        String beanName = toLowerFirstCase(method.getDeclaringClass().getSimpleName());

        Map<String, String[]> params = req.getParameterMap();

        Class<?>[] parameterTypes = method.getParameterTypes();

        Object[] parameterValues =  new Object[parameterTypes.length];

        for(int i = 0; i < parameterTypes.length; i++){
            Class parameterType = parameterTypes[i];
            if (parameterType == HttpServletRequest.class){
                parameterValues[i] = req;
                continue;
            }else if(parameterType == HttpServletResponse.class){
                parameterValues[i] = resp;
                continue;
            } else if(parameterType == String.class){

                // 这个是个错误的示例，这一步 是获取类的注解，
                // 并不能获取  这个类对象 在做为方法参数时的 注解
                GPRequestParam requestParam = (GPRequestParam)parameterType.getAnnotation(GPRequestParam.class);
                if(params.containsKey(requestParam.value())){ // 请求参数集合 是否包含

                    for (Map.Entry<String, String[]> param : params.entrySet()) {
                        String value = Arrays.toString(param.getValue())
                                        .replaceAll("\\[\\]","")
                                        .replaceAll("\\s",",");

                        parameterValues[i] = value;
                    }
                }
            }
        }


        try {
            Object obj = IOC.get(beanName);
            Object[] paramArr = new Object[]{req, resp, params.get("name")[0]};
            method.invoke(obj, paramArr);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    /**
     *  在v2 的基础上继续改造
     *  反射调用时，通过 注解的参数名 进行对应的赋值
     * @param req
     * @param resp
     */
    private void doDispatch_v3(HttpServletRequest req, HttpServletResponse resp) {

        // 绝对路径
        String url = req.getRequestURI();

        // 处理成相对路径
        String contextPath = req.getContextPath();

        url = url.replaceAll(contextPath, "").replaceAll("/+","/");

        if (!handllerMapping.containsKey(url)){
            try (PrintWriter writer = resp.getWriter()){
                writer.write("404 Not Found!!!");
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Method method = handllerMapping.get(url);

        // action 方法所在的类名
        String beanName = toLowerFirstCase(method.getDeclaringClass().getSimpleName());

        Map<String, String[]> params = req.getParameterMap();

        Class<?>[] parameterTypes = method.getParameterTypes();

        Object[] parameterValues =  new Object[parameterTypes.length];

        // 二维数组，第一层是 参数的位置，第二层 每个参数可以允许有多个注解
        Annotation[][] pa = method.getParameterAnnotations();

        for(int i = 0; i < parameterTypes.length; i++){
            Class parameterType = parameterTypes[i];
            if (parameterType == HttpServletRequest.class){
                parameterValues[i] = req;
                continue;
            }else if(parameterType == HttpServletResponse.class) {
                parameterValues[i] = resp;
                continue;
            }else if(parameterType == String[].class){
                System.out.println("数组类型的判断");
            } else if(parameterType == String.class){

                Annotation[] annotations = pa[i];
                for (Annotation annotation : annotations) {
                    if (annotation instanceof GPRequestParam){
                        String p_name = ((GPRequestParam) annotation).value();
                        if(params.containsKey(p_name)){ // 请求参数集合 是否包含

                            //  http://localhost:8080/mySpring/demo/query?name=tom&name=zhangsan
                            // 参数的值为数组类型，这里拼接成了一个串，一个key值对应一个数组
                            // 思考： 如果方法的参数是个 数组类型的参数
                            for (Map.Entry<String, String[]> param : params.entrySet()) {

                                // 这里硬性的将 参数都转为了 string 类型

                                String value = Arrays.toString(param.getValue())
                                        .replaceAll("\\[\\]","")
                                        .replaceAll("\\s",",");

                                parameterValues[i] = value;
                            }
                        }
                    }
                }

            }
        }


        try {
            Object obj = IOC.get(beanName);
            Object[] paramArr = new Object[]{req, resp, params.get("name")[0]};
            method.invoke(obj, parameterValues);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    /**
     *  反射调用时的参数类型转换改造
     *
     * @param req
     * @param resp
     */
    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) {

        // 绝对路径
        String url = req.getRequestURI();

        // 处理成相对路径
        String contextPath = req.getContextPath();

        url = url.replaceAll(contextPath, "").replaceAll("/+","/");

        if (!handllerMapping.containsKey(url)){
            try (PrintWriter writer = resp.getWriter()){
                writer.write("404 Not Found!!!");
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Method method = handllerMapping.get(url);

        // action 方法所在的类名
        String beanName = toLowerFirstCase(method.getDeclaringClass().getSimpleName());

        Map<String, String[]> params = req.getParameterMap();

        Class<?>[] parameterTypes = method.getParameterTypes();

        Object[] parameterValues =  new Object[parameterTypes.length];

        // 二维数组，第一层是 参数的位置，第二层 每个参数可以允许有多个注解
        Annotation[][] pa = method.getParameterAnnotations();

        for(int i = 0; i < parameterTypes.length; i++){
            Class parameterType = parameterTypes[i];
            if (parameterType == HttpServletRequest.class){
                parameterValues[i] = req;
                continue;
            }else if(parameterType == HttpServletResponse.class) {
                parameterValues[i] = resp;
                continue;
            }else if(parameterType == String[].class){
                System.out.println("数组类型的判断");
                continue;
            }
            //else if(parameterType == String.class){

            Annotation[] annotations = pa[i];
            for (Annotation annotation : annotations) {
                if (annotation instanceof GPRequestParam){
                    String p_name = ((GPRequestParam) annotation).value();
                    if(params.containsKey(p_name)){ // 请求参数集合 是否包含

                        //  http://localhost:8080/mySpring/demo/query?name=tom&name=zhangsan
                        // 参数的值为数组类型，这里拼接成了一个串，一个key值对应一个数组
                        // 思考： 如果方法的参数是个 数组类型的参数
                        // 这里硬性的将 参数都转为了 string 类型
                        String value = Arrays.toString(params.get(p_name))
                                    .replaceAll("\\[|\\]","")
                                .replaceAll("\\s",",");
                        Object convert = this.convert(parameterType, value);
                        parameterValues[i] = convert;

                    }
                }
            }

//            }
        }


        try {

            // 反射调用  对性能的消耗是非常高的
            Object obj = IOC.get(beanName);
            method.invoke(obj, parameterValues);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    /**
     *  URL 传递的参数都是 字符串类型的，需要将 String 转为任意类型
     * 类型转换
     * @param type
     * @param value
     * @return
     */
    private Object convert(Class<?> type, String value){
        if(Integer.class == type){
            return Integer.parseInt(value);
        }
        // 策略模式实现 类型转换

        return value;
    }

    private void initHandlerMapping() {

        if (IOC.isEmpty()) return ;

        for (Map.Entry<String, Object> entry : IOC.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();

            if (!(clazz.isAnnotationPresent(GPController.class))) continue;

            String baseUrl = "";
            if(clazz.isAnnotationPresent(GPRequestMapping.class)){
                GPRequestMapping requestMapping = clazz.getAnnotation(GPRequestMapping.class);
                baseUrl = requestMapping.value();
            }

            // 默认获取所有的 public 方法
            for (Method method : clazz.getMethods()) {

                if(!method.isAnnotationPresent(GPRequestMapping.class)) continue;
                GPRequestMapping requestMapping = method.getAnnotation(GPRequestMapping.class);
                String url = ("/" + baseUrl + "/" + requestMapping.value()).replaceAll("/+", "/");

                handllerMapping.put(url, method);

                System.out.println("Mapped :" + url + "," + method);

            }


        }

    }

    private void doAutowired() {

        if(IOC.isEmpty()) return;

        for (Map.Entry<String, Object> entry : IOC.entrySet()){

            // declared 所有的字段 包括 private protected default
            // 正常来说，普通的OOP 变成只能拿到 public 属性
            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();

            for (Field field: declaredFields){

                if (!field.isAnnotationPresent(GPAutowired.class)) continue;
                GPAutowired autowired = field.getAnnotation(GPAutowired.class);

                // 用户没有自定义 绑定的 beanName， 默认根据变量类型注入
                // 这里没有对首字母大小的判断
                String beanName = autowired.value().trim();
                if ("".equals(beanName)){
                    beanName = field.getType().getName();
                }

                // 如果是public 以外的修饰符，只要加了 @Autowired 注解，都要强制赋值
                // 反射中称为暴力访问。
                field.setAccessible(true);
                try {
                    field.set(entry.getValue(), IOC.get(beanName));

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private void doInstance() {

        //初始化，为 DI 做准备
        if(classNames.isEmpty()) return;
        try {

            for (String className: classNames){
                Class<?> clazz = Class.forName(className);

                if(clazz.isAnnotationPresent(GPController.class)){// 使用的是 GPController 注解

                    Object instance = clazz.newInstance();
                    String beanName = clazz.getSimpleName();
                    IOC.put(toLowerFirstCase(beanName), instance);
                }else if(clazz.isAnnotationPresent(GPService.class)){ // 使用的是 GPService 注解

                    GPService service = clazz.getAnnotation(GPService.class);
                    String beanName = service.value();
                    if("".equals(beanName.trim())){
                        beanName = toLowerFirstCase(clazz.getSimpleName());
                    }

                    Object instance = clazz.newInstance();
                    IOC.put(beanName, instance);

                    // 根究类型复制，如果一个接口有多个实现类  这里就会报出异常，这种情况是会出现的
                    // 可设置实现类是否是默认的实现，或是实现类进行有限级排序
                    for (Class<?> claz :clazz.getInterfaces()){
                        if (IOC.containsKey(claz.getName())){
                            throw new Exception("The “"+claz.getName()+"” has exists!");
                        }
                        IOC.put(claz.getName(), instance);
                    }
                }


            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private void doScanner(String scanPackage) {

        URL url = this.getClass().getClassLoader().getResource(File.separator + scanPackage.replace(".", File.separator));

        File classPath = new File(url.getFile());

        for (File file: classPath.listFiles()){
            if(file.isDirectory()){

                doScanner(scanPackage+"."+file.getName());
            }else{
                if(!file.getName().endsWith(".class")){continue;}
                classNames.add(scanPackage+"."+file.getName().replace(".class",""));
            }
        }


    }

    /**
     * 类名首字母小写
     * @param name
     * @return
     */
    private String toLowerFirstCase(String name) {

        // 这里可以判断一下 类的首字母 是否为大写，通过判断 ASCII 数值区间
        char[] chars = name.toCharArray();
        chars[0]+= 32;
        return String.valueOf(chars);

    }


    private void doLoadConfig(String contextConfigLocation) {

        // 自动关闭流，这种能自动关闭的流 都实现了了  AutoCloseable 接口
        // web.xml 中的初始化参数中，指定了配置文件的位置
        // 将 配置文件中的内容 加载到配置类中
        try(InputStream fis = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);) {
            contextConfig.load(fis);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
